package com.proj.service;

import com.proj.dao.SearchDao;
import com.proj.model.ResultModel;

import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/** 商品查询service */
@Service
public class SearchService {

  @Autowired private SearchDao searchDao;

  public ResultModel queryGoods(
      String productName,
      String fromPrice,
      String toPrice,
      String categoryId,
      String userId,
      String fromUpdateTime,
      String toUpdateTime,
      String fromPublicDate,
      String toPublicDate,
      String author,
      String appearance,
      String pressHorse,
      String sort,
      Integer pageIndex,
      Integer pageSize,
      String stylePrefix,
      String styleSuffix)
      throws Exception {
    // 根据参数创建查询对象
    SolrQuery solrQuery = new SolrQuery();

    // 默认搜索域
    solrQuery.set("df", "product_name");

    // 设置查询条件
    solrQuery.set("q", productName);

    // 商品分类过滤
    if (null != categoryId && !"".equals(categoryId)) {
      solrQuery.addFilterQuery("type_id:" + categoryId);
    }

    // 卖家过滤
    if (null != userId && !"".equals(userId)) {
      solrQuery.addFilterQuery("user_id:" + userId);
    }

    // 作者过滤
    if (null != author && !"".equals(author)) {
      solrQuery.addFilterQuery("product_writer:" + author);
    }

    // 品相过滤
    if (null != appearance && !"".equals(appearance)) {
      solrQuery.addFilterQuery("product_grade:" + appearance);
    }

    // 出版社过滤
    if (null != pressHorse && !"".equals(pressHorse)) {
      solrQuery.addFilterQuery("product_press:" + pressHorse);
    }

    // 更新时间区间过滤
    solrQuery.addFilterQuery("product_updatetime:[" + fromUpdateTime + " TO " + toUpdateTime + "]");

    // 出版时间区间过滤
    solrQuery.addFilterQuery(
        "product_publication_date:[" + fromPublicDate + " TO " + toPublicDate + "]");

    // 价格区间过滤
    solrQuery.addFilterQuery("product_price:[" + fromPrice + " TO " + toPrice + "]");

    try {
      // 排序条件
      String[] string = sort.split(" ");
      if (string[1].equals("desc")) {
        solrQuery.setSort(string[0], SolrQuery.ORDER.desc);
      } else {
        solrQuery.setSort(string[0], SolrQuery.ORDER.asc);
      }
    } catch (Exception allow) {

    }

    // 分页处理
    solrQuery.setStart(pageIndex * pageSize);
    solrQuery.setRows(pageSize);

    // 设置高亮
    solrQuery.setHighlight(true);
    solrQuery.addHighlightField("product_name");
    solrQuery.setHighlightSimplePre(stylePrefix);
    solrQuery.setHighlightSimplePost(styleSuffix);

    // 调用dao执行查询
    ResultModel resultModel = new SearchDao().search(solrQuery);

    // 根据总记录数计算总页数
    long recordCount = resultModel.getRecordCound();
    long pageCount = recordCount / pageSize;
    if (recordCount % pageSize > 0) {
      pageCount++;
    }
    resultModel.setPageCount((int) pageCount);
    resultModel.setCurPage(pageIndex);
    return resultModel;
  }
}
